package org.lzy.shop.order

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.textview.MaterialTextView

import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.adapter.OrderSpecAdapter
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityOrderinfoBinding
import org.lzy.shop.good.GoodInfoActivity
import org.lzy.shop.viewmodel.OrderModel

/**
 * 订单详情
 */
class OrderInfoActivity: BaseMvvmActivity<ActivityOrderinfoBinding, OrderModel>({ ActivityOrderinfoBinding.inflate(it) })  {
    //订单ID
    var orderID = 0
    //商品ID
    var goodID = 0
    //订单商品名
    var orderShopTitle: String? = ""

    override fun initView() {
        setTitleText(getResString(R.string.my_orderinfo))
        if (intent.extras != null) {
            val bundle = intent.extras
            orderID = bundle!!.getInt(Constant.ORDERID)
            orderShopTitle= bundle.getString(Constant.GOODSTITLE)
            goodID = bundle.getInt(Constant.GOODID)

        }
        binding.goodsSubName.text =orderShopTitle

        val orderInfoStatusScroll = findViewById<TextView>(R.id.order_info_status_scroll)
        val titleBar = findViewById<TextView>(R.id.title) // 这是include_head中的标题TextView
        val backButton = findViewById<ShapeableImageView>(R.id.back) // 这是返回按钮
        val appBarLayout = findViewById<AppBarLayout>(R.id.appBarLayout)

        // 设置滚动监听器，实现向上滑动时订单状态移动到标题栏的效果
        appBarLayout.addOnOffsetChangedListener {
                _, verticalOffset ->

            // 当向上滑动时（verticalOffset < 0）
            if (verticalOffset < 0) {
                // 1. 隐藏标题栏下方显示的订单状态
                orderInfoStatusScroll.visibility = View.GONE

                // 2. 将订单状态文本显示在标题栏中
                titleBar.text = orderInfoStatusScroll.text

                // 3. 调整标题栏文本的位置，使其靠左，靠近返回按钮
                val params = titleBar.layoutParams as ConstraintLayout.LayoutParams
                params.startToStart = ConstraintLayout.LayoutParams.UNSET
                params.endToEnd = ConstraintLayout.LayoutParams.UNSET
                params.startToEnd = backButton.id // 将标题定位在返回按钮的右侧
                params.marginStart = resources.getDimensionPixelSize(R.dimen.dp_8) // 增加间距
                titleBar.layoutParams = params
            } else {
                // 当向下滑动回到顶部时（verticalOffset == 0）
                // 1. 显示标题栏下方的订单状态
                orderInfoStatusScroll.visibility = View.VISIBLE

                // 2. 恢复标题栏的原始标题
                titleBar.text =getResString(R.string.my_orderinfo)

                // 3. 将标题栏文本恢复为居中显示
                val params = titleBar.layoutParams as ConstraintLayout.LayoutParams
                params.startToStart = ConstraintLayout.LayoutParams.PARENT_ID
                params.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
                params.startToEnd = ConstraintLayout.LayoutParams.UNSET
                params.marginStart = 0
                titleBar.layoutParams = params
            }
        }
    }

    override fun requestData() {
        //获取订单详情
        mViewModel.getOrderInfo(orderID)

    }

    override fun initData() {
        //订单详情回调
        mViewModel.orderInfoData.observeWithLifecycle(this){orderInfoResponse ->
            orderInfoResponse?.let {
                val addressShow= StringBuilder()
                addressShow.append(orderInfoResponse.address?.province).append(orderInfoResponse.address?.city).append(orderInfoResponse.address?.district)
                binding.showAddressTxt.text = addressShow.toString()
                binding.showSpecaddressTxt.text=orderInfoResponse.address?.address
                val contractShow= StringBuilder()
                contractShow.append(orderInfoResponse.address?.contact).append(orderInfoResponse.address?.phone)
                binding.showContract.text=contractShow.toString()

                val orderSpecAdapter = OrderSpecAdapter()
                binding.shopTv.apply {
                    layoutManager= LinearLayoutManager(this@OrderInfoActivity, LinearLayoutManager.VERTICAL, false)
                    adapter=orderSpecAdapter
                }
                orderSpecAdapter.submitList(orderInfoResponse.goodsList)
                binding.goodsAllprice.text = orderInfoResponse.price.toString()
                binding.chooseCouponName.text = orderInfoResponse.discountPrice.toString()
                //自己计算使用优惠劵的价格
                val result = orderInfoResponse.price - orderInfoResponse.discountPrice
                binding.goodsTotalprice.text =result.toString()
                binding.orderNum.text =orderInfoResponse.orderNum
                binding.createTime.text =orderInfoResponse.createTime
                //订单备注
                if (TextUtils.isEmpty(orderInfoResponse.remark)) {
                    binding.remark.text ="无"
                }else{
                    binding.remark.text = orderInfoResponse.remark
                }

                //支付方式，2是微信，1是支付宝
                if (orderInfoResponse.payType==2){
                    binding.payType.text = "微信"
                }else{
                    binding.payType.text = "支付宝"
                }

                //支付时间
                binding.payTime.text = orderInfoResponse.payTime

                 //底部状态按钮显示
                if (orderInfoResponse.status == 0) {
                    binding.tvPaymentOrder.visibility= View.VISIBLE
                    binding.tvCancelOrder.visibility= View.VISIBLE
                    binding.orderInfoStatusScroll.text="已关闭"
                } else if (orderInfoResponse.status == 1) {
                    binding.tvApplyReturn.visibility= View.VISIBLE
                    binding.tvBuyAgain.visibility= View.VISIBLE
                    binding.orderInfoStatusScroll.text="待发货"
                } else if (orderInfoResponse.status == 2) {
                    binding.tvApplyReturn.visibility= View.VISIBLE
                    binding.tvConfirmDeliverGoods.visibility= View.VISIBLE
                    binding.checkLogisticsTv.visibility= View.VISIBLE
                    binding.tvBuyAgain.visibility= View.VISIBLE
                    binding.orderInfoStatusScroll.text="待收货"
                } else if (orderInfoResponse.status == 3) {
                    binding.checkLogisticsTv.visibility= View.VISIBLE
                    binding.tvBuyAgain.visibility= View.VISIBLE
                    binding.orderComment.visibility= View.VISIBLE
                    binding.orderInfoStatusScroll.text="待评价"
                } else if (orderInfoResponse.status == 4) {
                    binding.checkLogisticsTv.visibility= View.VISIBLE
                    binding.orderComment.visibility= View.VISIBLE
                    binding.tvBuyAgain.visibility= View.VISIBLE
                    binding.tvConfirmDeliverGoods.visibility= View.GONE
                    binding.tvApplyReturn.visibility= View.GONE
                    binding.orderInfoStatusScroll.text="交易完成"
                } else if (orderInfoResponse.status == 5) {
                    binding.tvBuyAgain.visibility= View.VISIBLE
                    binding.checkLogisticsTv.visibility= View.VISIBLE
                    binding.orderInfoStatusScroll.text="退款中"
                } else if (orderInfoResponse.status == 6) {
                    binding.tvApplyReturn.visibility= View.VISIBLE
                    binding.tvBuyAgain.visibility= View.VISIBLE
                    binding.checkLogisticsTv.visibility= View.VISIBLE
                    binding.orderInfoStatusScroll.text="已退款"
                } else if (orderInfoResponse.status == 7) {
                    binding.orderInfoStatusScroll.text="已关闭"
                }
            }

        }

        //取消订单回调
        mViewModel.orderOpertionData.observeWithLifecycle(this){string ->
            dismissLoading()
            showToast(getResString(R.string.ordercancel_success))
            finish()
        }
        //确认收获
        mViewModel.orderConfirmData.observeWithLifecycle(this){string ->
            dismissLoading()
            showToast(getResString(R.string.orderdeliver_success))
            finish()
        }
        //订单退款
        mViewModel.orderRefundData.observeWithLifecycle(this){string ->
            dismissLoading()
            showToast(getResString(R.string.refund_success))
            finish()
        }

    }

    override fun allClick() {
        //去评价
        binding.orderComment.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDERID, orderID)
            startActivity(OrderCommentActivity::class.java, bundle)
        }
        //再次购买
        binding.tvBuyAgain.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.GOODID, goodID)
            startActivity(GoodInfoActivity::class.java, bundle)
        }
        //查看物流
        binding.checkLogisticsTv.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDERID, orderID)
            startActivity(LogisticsListActivity::class.java, bundle)
        }
        //取消订单
        binding.tvCancelOrder.setOnClickListener {
            CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.dialog_common) {
                override fun onBind(dialog: CustomDialog?, v: View?) {
                    val showText = v?.findViewById<TextView>(R.id.txt_msg)
                    val showTitle = v?.findViewById<TextView>(R.id.txt_title)
                    showText?.text = getResString(R.string.confirm_order_hint)
                    showTitle?.text = getResString(R.string.confirm_deliverygoods)
                    val btnOk = v?.findViewById<MaterialTextView>(R.id.btn_pos)
                    val btnCancel = v?.findViewById<MaterialTextView>(R.id.btn_neg)
                    btnOk?.setOnClickListener {
                        dialog?.dismiss()
                        showLoading()
                        mViewModel.confirmOrder(orderID)
                    }
                    btnCancel?.setOnClickListener { dialog?.dismiss() }
                }
            }).setMaskColor("#4D000000".toColorInt())
        }
        //退款
        binding.tvRefunded.setOnClickListener {
            val  bundle= Bundle()
            bundle.putInt(Constant.ORDERID,orderID)
            startActivity(OrderInfoActivity::class.java,bundle)
            finish()
        }
        //确认收获
        binding.tvConfirmDeliverGoods.setOnClickListener {
            CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.dialog_common) {
                override fun onBind(dialog: CustomDialog?, v: View?) {
                    val showText = v?.findViewById<TextView>(R.id.txt_msg)
                    val showTitle = v?.findViewById<TextView>(R.id.txt_title)
                    showText?.text = getResString(R.string.confirm_order_hint)
                    showTitle?.text = getResString(R.string.confirm_deliverygoods)
                    val btnOk = v?.findViewById<MaterialTextView>(R.id.btn_pos)
                    val btnCancel = v?.findViewById<MaterialTextView>(R.id.btn_neg)
                    btnOk?.setOnClickListener {
                        dialog?.dismiss()
                        showLoading()
                        mViewModel.confirmOrder(orderID)
                    }
                    btnCancel?.setOnClickListener { dialog?.dismiss() }
                }
            }).setMaskColor("#4D000000".toColorInt())
        }
    }
}